/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by WangYunlai on 2022/6/27.
//

#include "sql/operator/update_physical_operator.h"
#include "common/log/log.h"
#include "storage/table/table.h"
#include "storage/trx/trx.h"

RC UpdatePhysicalOperator::open(Trx *trx)
{
  if (children_.empty()) {
    return RC::SUCCESS;
  }

  unique_ptr<PhysicalOperator> &child = children_[0];

  RC rc = child->open(trx);
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to open child operator: %s", strrc(rc));
    return rc;
  }

  trx_ = trx;

  while (OB_SUCC(rc = child->next())) {
    Tuple *tuple = child->current_tuple();
    if (nullptr == tuple) {
      LOG_WARN("failed to get current record: %s", strrc(rc));
      return rc;
    }

    RowTuple *row_tuple = static_cast<RowTuple *>(tuple);
    Record   &record    = row_tuple->record();
    records_.emplace_back(std::move(record));
  }

  child->close();

  // return RC::UNIMPLEMENTED;
  if(records_.empty()) {
    LOG_WARN("no records to update");
    return RC::SUCCESS; // 没有记录需要更新
  }
  vector<Value> values_;
  for (const auto &expr : expressions_) {
    Value value;
    rc = expr->try_get_value(value);
    if (rc != RC::SUCCESS) {
      if(rc== RC::RECORD_EOF) {
        value.set_null();
      }
      else
      {
        LOG_WARN("failed to evaluate expression: %s", strrc(rc));
        return rc;
      }
    
    }
    if(expr->type()==ExprType::SUBQUERY) {
      rc = expr->try_get_value(value);
      if(rc!=RC::RECORD_EOF)
      {
        LOG_WARN("subquery in update must return only one row");
        return RC::SUBQUERY_INVALID_ROW_NUM;
      }
    }
    if(value.length()>65535){
      LOG_WARN("value length exceeds limit: %d", value.length());
      return RC::INVALID_ARGUMENT;
    }
    values_.emplace_back(std::move(value));
  }

  for(int i=0;i<attrs_.size();i++) {
    const FieldMeta *field = table_->table_meta().field(attrs_[i].c_str());
    if(!field->nullable()) {
      if(values_[i].attr_type()==AttrType::NULLS) {
        LOG_WARN("not nullable field %s cannot be null", field->name());
        return RC::SUBQUERY_INVALID_ROW_NUM; //这里为了方便报错，返回这个return code
      }
    }
  }

 for (Record &record : records_) {
    Record new_record;
    rc = table_->modify_record(static_cast<int>(values_.size()), values_.data(), attrs_, new_record, record);
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to modify record: %s", strrc(rc));
      return rc;
    }
    vector<Value> old_values;
    vector<Value> new_values;
    rc = trx_->update_record(table_, record, new_record, old_values, new_values);
    if (rc != RC::SUCCESS) {
      LOG_WARN("failed to update record: %s", strrc(rc));
      return rc;
    }
 }

  return RC::SUCCESS; 
}

RC UpdatePhysicalOperator::next()
{
  return RC::RECORD_EOF;
}

RC UpdatePhysicalOperator::close()
{
  return RC::SUCCESS;
}
